package org.jinyan.wechat.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jinyan.constant.SystemConstants;
import org.jinyan.wechat.service.WechatService;
import org.jinyan.wechat.utils.WechatMessageUtil;

public class WechatServlet extends HttpServlet {
	private static final long serialVersionUID = 4440739483644821986L;

	private Logger logger = Logger.getLogger(WechatServlet.class);

	/**
	 * 确认请求来自微信服务器
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String echostr = request.getParameter("echostr");
		if (checkWeixinReques(request) && echostr != null) {
			out.print(echostr);
		} else {
			out.print("error");
		}
		// out.flush();
		out.close();
		out = null;

	}

	/**
	 * 处理微信服务器发来的消息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("处理微信服务器发来的消息 doPost start  request="
				+ request.getLocalAddr());
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 调用核心业务类接收消息、处理消息

		String respMessage = WechatService.processRequest(request);
		System.out.println("调用核心业务类接收消息、处理消息 respMessage=" + respMessage);
		logger.info("调用核心业务类接收消息、处理消息 respMessage=" + respMessage);
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.flush();
		out.close();
		out = null;
	}

	/**
	 * 根据token计算signature验证是否为weixin服务端发送的消息
	 */
	private static boolean checkWeixinReques(HttpServletRequest request) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		if (signature != null && timestamp != null && nonce != null) {
			String[] strSet = new String[] { SystemConstants.TOKEN, timestamp,
					nonce };
			java.util.Arrays.sort(strSet);
			String key = "";
			for (String string : strSet) {
				key = key + string;
			}
			String pwd = WechatMessageUtil.sha1(key);
			return pwd.equals(signature);
		} else {
			return false;
		}
	}

}
